<template>
  <div class="container">
    <div class="app-container">
      <!-- 加上el-scrollbar 以后,左侧菜单就会出现滚动条,不会影响右侧表格 -->
      <el-scrollbar>
        <div class="left">
          <el-input
            v-model="params.keyword"
            style="margin-bottom:10px"
            type="text"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="输入员工姓名全员搜索"
            clearable
            @input="secrchEmlpoyee"
            @clear="clear"
          />
          <!-- 树形组件 -->
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="{ label: 'name' }"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current
            node-key="id"
            @node-click="nodeClick"
          />
        </div>
      </el-scrollbar>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
          >添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData">
          <el-table-column label="头像" align="center" prop="staffPhoto">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 2 ? '非正式' : '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作">
            <template #default="{ row }">
              <!-- <el-button type="text" @click="$router.push(`/employee/detail?id=${row.id}`)">查看</el-button> -->
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="showAssignDialog(row.id)">角色</el-button>
              <el-popconfirm title="确定要删除该员工吗吗？" @confirm="delEmployee(row.id)">
                <el-button slot="reference" type="text" style="margin-left: 10px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="float:right; margin:20px 50px">
          <el-col :span="12">
            <el-pagination
              :current-page="params.page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="params.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- excel表格 -->
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @reload="getEmployee" />
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="visible">
      <!-- 复选框 -->
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in roles" :key="item.id" style="margin:10px" :label="item.id" size="medium">{{ item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <div style="text-align:center">
        <el-button type="primary" @click="assignRole">确定</el-button>
        <el-button @click="visible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImportExcel from './components/import-excel'
// 导入导出的包
import FileSaver from 'file-saver'
import { reqGetDepts } from '@/api/department'
import { reqGetEmployees, reqExportExcel, reqDelEmployee, reqGetDetail, reqAssignRoles } from '@/api/employee'
// 调用树形结构的数据
import { translatetoTreeDate } from '@/utils'
import { reqGetEnableEoles } from '../../api/role'
let timer = null
export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      treeData: [],
      params: {
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      tableData: [],
      total: 0,
      showExcelDialog: false,
      visible: false, // 分配角色的弹出框
      roles: [], // 已启用的角色列表
      checkList: [], // 被选中的角色列表
      id: 0
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 调用获取部门的请求
    async getDepts() {
      const res = await reqGetDepts()
      // 使用之前封装的转树形结构的方法 ,将树形结构赋值给treeData中,渲染树形控件
      this.treeData = translatetoTreeDate(res.data, 0)
      // 默认记录第一个部门的id,这个接口有问题,一会是1,一会是0
      this.params.departmentId = this.treeData[0].id
      // 由于更新dom是异步的,需要使用this.$nextTick
      // this.$nextTick(() => {
      //   this.$refs.treeRef.setCurrentKey(this.params.departmentId)
      // })
      // 或者 $this.$nextTick是promise对象,代表异步更新完成之前,所以可以等待
      await this.$nextTick()
      this.$refs.treeRef.setCurrentKey(this.params.departmentId)
      // 在设置完点击部门的id的时候,在发请求,如果在其他地方发请求,params里面的那个绑定的id可能还没有赋值
      this.getEmployee()
    },
    // 设置第一个高亮
    nodeClick(data) {
      this.params.departmentId = data.id
      // 点击高亮的时候,通过id在进行发送请求
      // 切换部门后,将页码设置为1
      this.params.page = 1
      this.getEmployee()
    },
    // 获取员工列表
    async getEmployee() {
      const { data } = await reqGetEmployees(this.params)
      // console.log(data)
      this.tableData = data.rows
      this.total = data.total
    },
    // 显示页码
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.params.pagesize = val
      this.getEmployee()
    },
    // 显示当前页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.params.page = val
      this.getEmployee()
    },
    // 输入框查询员工
    secrchEmlpoyee() {
      // 判空
      if (!this.params.keyword.trim()) return
      // 发起请求
      this.params.page = 1
      // 开启定时器之前要清除上一个定时器
      clearTimeout(timer)
      timer = setTimeout(async() => {
        await this.getEmployee()
      }, 500)
    },
    // 点击清除的时候,获取所有的员工
    clear() {
      this.params.page = 1
      // this.params.departmentId = this.treeData[0].id
      this.getEmployee()
    },
    // 导出
    async exportExcel() {
      const res = await reqExportExcel()
      console.log(res)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除员工
    async delEmployee(id) {
      await reqDelEmployee(id)
      // 判断是否是最后一个
      if (this.tableData.length === 1 && this.params.page > 1) this.params.page--
      this.getEmployee()
    },
    // 点击角色 获取所有启用的角色 获取所有已启用的角色
    async showAssignDialog(id) {
      this.id = id
      //   const res = await reqGetEnableEoles()
      //   // console.log(res)
      //   this.roles = res.data
      //   const { data } = await reqGetDetail(id)
      //   console.log(data)
      //   this.checkList = data.roleIds
      // 优化代码
      Promise.all([reqGetEnableEoles(), reqGetDetail(id)]).then(values => {
        console.log(values)
        this.roles = values[0].data
        this.checkList = values[1].data.roleIds
        // 为了优化，获取完成之后在打开对话框
        this.visible = true
      })
    },
    // 分配角色
    async assignRole() {
      await reqAssignRoles(this.id, this.checkList)
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  // height: 1000px;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
